package com.baizhi.service.impl;

import com.baizhi.entity.Book;
import com.baizhi.entity.Category;
import com.baizhi.mapper.BookMapper;
import com.baizhi.mapper.CategoryMapper;
import com.baizhi.service.CategoryService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service("categoryService")
@Transactional
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper mapper;
    @Autowired
    private BookMapper bookMapper;
    @Override
    public PageInfo<Category> selectPage(Integer pageNum, Integer pageSize) {
        List<Category> categories = mapper.selectAll(pageNum, pageSize);
        PageInfo<Category> pageInfo=new PageInfo<>(categories,10);
        return pageInfo;
    }

    @Override
    public void removeCategory(Integer id) {
        if(bookMapper.selectCount(id)>0){
            throw new RuntimeException("类别有图书，不能删除");
        }
        if(mapper.selectAllParentId(id)>0){
            throw new RuntimeException("类别下有子类别，不能删除");
        }
        mapper.removeCategory(id);
    }

    @Override
    public List<Category> select() {
        return mapper.selectAllCategoryId();
    }

    @Override
    public void addFirst(Category category) {
        if(mapper.selectByName(category.getName())!=null){
            throw new RuntimeException("该类别已存在，无需添加");
        }
        mapper.addCategory(category);
    }

    @Override
    public List<Category> selectLevel1() {
        return mapper.selectLevel1();
    }

    @Override
    public List<Category> selectLevel2() {
        return mapper.selectLevel2();
    }

    @Override
    public List<Category> selectChild() {
        return mapper.selectChild();
    }

    @Override
    public List<Category> selectByParentId(Integer id) {
        return mapper.selectByParentId(id);
    }

    @Override
    public Category selectCategory(Integer id) {
        return mapper.selectCategory(id);
    }
}
